package com.nursinghome.admin.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nursinghome.admin.service.MedicalStaffService;
import com.nursinghome.admin.service.SalaryService;
import com.nursinghome.bean.RespBean;
import com.nursinghome.bean.Salary;
import com.nursinghome.exception.NurisingHomeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;


@CrossOrigin
@RestController
@RequestMapping("/admin/salary")
public class SalaryController {
    @Autowired
    private SalaryService salaryService;
    @Autowired
    private MedicalStaffService medicalStaffService;
    //根据月份查询工资单
    @GetMapping
    public RespBean selectByPicday(Integer pageNum, String data) {
        if (data.length()>0 && data!=null){
            ZonedDateTime zdt = ZonedDateTime.parse(data);
            // 加上八小时
            ZonedDateTime newZdt = zdt.plusHours(8);
            // 转换为字符串
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
            data = newZdt.format(formatter);
        }
        PageHelper.startPage(pageNum, 6);
        List<Salary> salaries = salaryService.selectByPicday(data);
        PageInfo<Salary> pageInfo = new PageInfo<>(salaries);
        return RespBean.ok("",pageInfo);
    }
    @PostMapping
    //新增工资条
    public RespBean insert(@RequestBody @Validated() Salary salary) throws NurisingHomeException {
        if (salaryService.insert(salary)){
            return RespBean.ok("新增成功");
        }
        return RespBean.error("新增失败");
    }
    @PutMapping
    //修改工资条
    public RespBean update(Salary salary) throws NurisingHomeException {
        salaryService.update(salary);
        return RespBean.ok("修改成功");
    }

    @GetMapping("/mid")
    //根据月份和mid查询工资条
    public RespBean selectByMid(String data, Integer mid) {
        Salary salary = salaryService.selectByMid(data, mid);
        if (salary == null){
            return RespBean.error("");
        }
        return RespBean.ok("",salary);
    }
    //查询所有的员工
    @GetMapping("/allMedical")
    public RespBean allMedical(){
        List<HashMap<String, Object>> list = medicalStaffService.selectAll("", "", "")
                .stream()
                .filter(m -> m.getMstate() == 1)
                .map(m -> {
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("mid", m.getMid());
                    map.put("values", m.getMno() + "-" + m.getMname());
                    return map;
                })
                .collect(Collectors.toList());
        return RespBean.ok("",list);
    }
}
